package com.haiheng.voiceandbook.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.haiheng.bookmusic.base.BaseActivity;
import com.haiheng.library.log.LogUtils;
import com.haiheng.voiceandbook.R;
import com.haiheng.voiceandbook.databinding.DialogBookShowBinding;

import org.geometerplus.android.fbreader.AppNotifier;
import org.geometerplus.android.fbreader.NotificationUtil;
import org.geometerplus.android.fbreader.TOCActivity;
import org.geometerplus.android.fbreader.api.ApiListener;
import org.geometerplus.android.fbreader.api.ApiServerImplementation;
import org.geometerplus.android.fbreader.api.FBReaderIntents;
import org.geometerplus.android.fbreader.api.PluginApi;
import org.geometerplus.android.fbreader.dict.DictionaryUtil;
import org.geometerplus.android.fbreader.libraryService.BookCollectionShadow;
import org.geometerplus.android.fbreader.tips.TipsActivity;
import org.geometerplus.android.util.OrientationUtil;
import org.geometerplus.android.util.UIMessageUtil;
import org.geometerplus.android.util.UIUtil;
import org.geometerplus.fbreader.Paths;
import org.geometerplus.fbreader.book.Book;
import org.geometerplus.fbreader.book.BookUtil;
import org.geometerplus.fbreader.book.Bookmark;
import org.geometerplus.fbreader.bookmodel.BookModel;
import org.geometerplus.fbreader.bookmodel.TOCTree;
import org.geometerplus.fbreader.fbreader.ActionCode;
import org.geometerplus.fbreader.fbreader.FBReaderApp;
import org.geometerplus.fbreader.fbreader.options.ColorProfile;
import org.geometerplus.fbreader.tips.TipsManager;
import org.geometerplus.zlibrary.core.application.ZLApplication;
import org.geometerplus.zlibrary.core.application.ZLApplicationWindow;
import org.geometerplus.zlibrary.core.filesystem.ZLFile;
import org.geometerplus.zlibrary.core.options.Config;
import org.geometerplus.zlibrary.core.util.ZLColor;
import org.geometerplus.zlibrary.core.view.ZLViewWidget;
import org.geometerplus.zlibrary.ui.android.library.ZLAndroidApplication;
import org.geometerplus.zlibrary.ui.android.library.ZLAndroidLibrary;
import org.geometerplus.zlibrary.ui.android.view.AndroidFontUtil;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;


/**
 * 对话框工具类
 *
 * @author weishixiong
 * @Time 2018-07-4
 */
public class OpenBookDialog extends Dialog implements ZLApplicationWindow {
//    var bookShowBinding: DialogBookShowBinding? = null

    private FBReaderApp myFBReaderApp;
    private volatile Book myBook;
    private DialogBookShowBinding bookShowBinding;
    private Activity activity;
    private FBReaderApp.Notifier myNotifier = null;
    private final List<PluginApi.ActionInfo> myPluginActions =
            new LinkedList<PluginApi.ActionInfo>();
    private static final String PLUGIN_ACTION_PREFIX = "___";
    private final BroadcastReceiver myPluginInfoReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final ArrayList<PluginApi.ActionInfo> actions = getResultExtras(true).<PluginApi.ActionInfo>getParcelableArrayList(PluginApi.PluginInfo.KEY);
            if (actions != null) {
                synchronized (myPluginActions) {
                    int index = 0;
                    while (index < myPluginActions.size()) {
                        myFBReaderApp.removeAction(PLUGIN_ACTION_PREFIX + index++);
                    }
                    myPluginActions.addAll(actions);
                    index = 0;
                    for (PluginApi.ActionInfo info : myPluginActions) {
//						myFBReaderApp.addAction(
//							PLUGIN_ACTION_PREFIX + index++,
//							new RunPluginAction(NewFBReaderActivity.this, myFBReaderApp, info.getId())
//						);
                    }
                }
            }
        }
    };

    public OpenBookDialog(Activity context,DialogBookShowBinding binding, View view) {
        super(context, R.style.my_dialog_style);
        this.bookShowBinding= binding;
        this.activity = context;
        this.setCancelable(true);
        this.setCanceledOnTouchOutside(true);
        this.setContentView(view);
        Window win = this.getWindow();
        win.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = win.getAttributes();
        lp.width = WindowManager.LayoutParams.FILL_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        win.setAttributes(lp);
        initFbread();

    }

    private void onstart(){
        getCollection().bindToService(activity, new Runnable() {
            public void run() {
                new Thread() {
                    public void run() {
                        getPostponedInitAction().run();
                    }
                }.start();
                myFBReaderApp.getViewWidget().repaint();
            }
        });

        initPluginActions();

        final ZLAndroidLibrary zlibrary = getZLibrary();

        Config.Instance().runOnConnect(new Runnable() {
            public void run() {
                zlibrary.ShowStatusBarOption.saveSpecialValue();
                myFBReaderApp.ViewOptions.ColorProfileName.saveSpecialValue();
            }
        });
    }



    private void initFbread() {
        myFBReaderApp = (FBReaderApp)FBReaderApp.Instance();
        if (myFBReaderApp == null) {
            myFBReaderApp = new FBReaderApp(Paths.systemInfo(activity), new BookCollectionShadow());
        }
        getCollection().bindToService(activity, null);
        myBook = null;
        myFBReaderApp.setWindow(this);
        myFBReaderApp.initWindow();
        myNotifier  = new AppNotifier(activity);


        //背景颜色/字体颜色初始化
        ColorProfile colorProfile = myFBReaderApp.ViewOptions.getColorProfile();
        ZLColor zlBgColor = new ZLColor(activity.getColor(R.color.white));
//        ZLColor zlFontColor = new ZLColor(ThemeStyle.getFontColor());
        colorProfile.WallpaperOption.setValue("");//无图片背景,所有清空，后期扩展
        colorProfile.BackgroundOption.setValue(zlBgColor);

    }

    private void initPluginActions() {
        synchronized (myPluginActions) {
            int index = 0;
            while (index < myPluginActions.size()) {
                myFBReaderApp.removeAction(PLUGIN_ACTION_PREFIX + index++);
            }
            myPluginActions.clear();
        }

        activity.sendOrderedBroadcast(
                new Intent(PluginApi.ACTION_REGISTER),
                null,
                myPluginInfoReceiver,
                null,
                activity.RESULT_OK,
                null,
                null
        );
    }


    private Runnable getPostponedInitAction() {
        return new Runnable() {
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    public void run() {
                        new TipRunner().start();
                        DictionaryUtil.init(activity, null);
                        final Intent intent = activity.getIntent();
                        if (intent != null && FBReaderIntents.Action.PLUGIN.equals(intent.getAction())) {
//							new RunPluginAction(NewFBReaderActivity.this, myFBReaderApp, intent.getData()).run();
                        }
                    }
                });
            }
        };
    }
    private class TipRunner extends Thread {
        TipRunner() {
            setPriority(MIN_PRIORITY);
        }

        public void run() {
            final TipsManager manager = new TipsManager(Paths.systemInfo(activity));
            switch (manager.requiredAction()) {
                case Initialize:
                    activity.startActivity(new Intent(
                            TipsActivity.INITIALIZE_ACTION, null, activity, TipsActivity.class
                    ));
                    break;
                case Show:
                    activity.startActivity(new Intent(
                            TipsActivity.SHOW_TIP_ACTION, null, activity, TipsActivity.class
                    ));
                    break;
                case Download:
                    manager.startDownloading();
                    break;
                case None:
                    break;
            }
        }
    }



    private BookCollectionShadow getCollection() {
        return (BookCollectionShadow)myFBReaderApp.Collection;
    }

    public ZLAndroidLibrary getZLibrary() {
        return ((ZLAndroidApplication)activity.getApplication()).library();
    }

    public synchronized void openBook(Intent intent, String title) {
        if ( myBook != null) {
            BookModel model = myFBReaderApp.Model;
            if (model != null){
                TOCTree tocTree =  model.TOCTree;
                openBookText(tocTree,title);
            }
            return;
        }

        myBook = FBReaderIntents.getBookExtra(intent, myFBReaderApp.Collection);
        final Bookmark bookmark = FBReaderIntents.getBookmarkExtra(intent);
        if (myBook == null) {
            final Uri data = intent.getData();
            if (data != null) {
                myBook = createBookForFile(ZLFile.createFileByPath(data.getPath()));
            }
        }
        if (myBook != null) {
            ZLFile file = BookUtil.fileByBook(myBook);
            if (!file.exists()) {
                if (file.getPhysicalFile() != null) {
                    file = file.getPhysicalFile();
                }
                UIMessageUtil.showErrorMessage(activity, "fileNotFound", file.getPath());
                myBook = null;
            } else {
                NotificationUtil.drop(activity, myBook);
            }
        }
        Config.Instance().runOnConnect(new Runnable() {
            public void run() {
                myFBReaderApp.openBook(myBook, bookmark, new Runnable() {
                    @Override
                    public void run() {
                        BookModel model = myFBReaderApp.Model;
                        if (model != null){
                            TOCTree tocTree =  model.TOCTree;
                            openBookText(tocTree,title);
                        }                    }
                }, myNotifier);
                AndroidFontUtil.clearFontCache();

            }
        });

//        opentes();
//        onstart();
    }
    void openBookText(TOCTree tocTree ,String title) {
        if (tocTree.subtrees() != null && tocTree.subtrees().size()> 0){
            for (TOCTree tree : tocTree.subtrees()) {
                if (tree.getText().equals(title)){
                    skipToTocTree(tree);
                    break;
                }
                if (tree.subtrees() != null && tree.subtrees().size() > 0){
                    openBookText(tree,title);
                }else {
                    if (tree.getText().equals(title)){
                        skipToTocTree(tree);
                        break;
                    }
                }
            }
        }
    }

    private void skipToTocTree(TOCTree tree){
        final TOCTree.Reference reference = tree.getReference();
        if (reference != null) {
            final FBReaderApp fbreader = (FBReaderApp)ZLApplication.Instance();
            fbreader.addInvisibleBookmark();
            fbreader.BookTextView.gotoPosition(reference.ParagraphIndex, 0, 0);
            fbreader.showBookTextView();
            fbreader.storePosition();
        }
    }

    private void opentes(){
//        ReadPopupPanel.restoreVisibilities(myFBReaderApp);
        ApiServerImplementation.sendEvent(activity, ApiListener.EVENT_READ_MODE_OPENED);
    }


    public void openMenu(){
        //本书目录
//        myFBReaderApp.addAction(ActionCode.SHOW_TOC, new ShowTOCAction(activity, myFBReaderApp));
//        BookModel model = myFBReaderApp.Model;
//        if (model != null && model.TOCTree.hasChildren()){
//            TOCTree tocTree = model.TOCTree;
//        }


        OrientationUtil.startActivity(
                activity, new Intent(activity, TOCActivity.class)
        );

        //显示菜单
//        myFBReaderApp.addAction(ActionCode.SHOW_MENU, new ShowMenuAction(this, myFBReaderApp));
    }

    private Book createBookForFile(ZLFile file) {
        if (file == null) {
            return null;
        }
        Book book = myFBReaderApp.Collection.getBookByFile(file.getPath());
        if (book != null) {
            return book;
        }
        if (file.isArchive()) {
            for (ZLFile child : file.children()) {
                book = myFBReaderApp.Collection.getBookByFile(child.getPath());
                if (book != null) {
                    return book;
                }
            }
        }
        return null;
    }


    @Override
    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) {
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void setWindowTitle(String title) {

    }

    @Override
    public void showErrorMessage(String key) {
        UIMessageUtil.showErrorMessage(activity, key);
    }

    @Override
    public void showErrorMessage(String resourceKey, String parameter) {
        UIMessageUtil.showErrorMessage(activity, resourceKey, parameter);
    }

    @Override
    public ZLApplication.SynchronousExecutor createExecutor(String key) {
        return UIUtil.createExecutor(activity, key);
    }

    @Override
    public void processException(Exception e) {

    }

    @Override
    public void refresh() {
        activity.runOnUiThread(new Runnable() {
            public void run() {
//                for (Map.Entry<MenuItem,String> entry : myMenuItemMap.entrySet()) {
//                    final String actionId = entry.getValue();
//                    final MenuItem menuItem = entry.getKey();
//                    menuItem.setVisible(myFBReaderApp.isActionVisible(actionId) && myFBReaderApp.isActionEnabled(actionId));
//                    switch (myFBReaderApp.isActionChecked(actionId)) {
//                        case TRUE:
//                            menuItem.setCheckable(true);
//                            menuItem.setChecked(true);
//                            break;
//                        case FALSE:
//                            menuItem.setCheckable(true);
//                            menuItem.setChecked(false);
//                            break;
//                        case UNDEFINED:
//                            menuItem.setCheckable(false);
//                            break;
//                    }
//                }
            }
        });

    }

    @Override
    public boolean dispatchTouchEvent(@NonNull MotionEvent ev) {
        if (activity instanceof BaseActivity){
            ((BaseActivity) activity).updateUserActionTime();
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public ZLViewWidget getViewWidget() {
        return bookShowBinding.bookView;
    }

    @Override
    public void close() {
        dismiss();
    }

    @Override
    public int getBatteryLevel() {
        return 0;
    }
}
